//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import BottomNav from '@/components/BottomNav';
import { useStores } from '@/hooks';
import type { IRouteConfig } from '@/routes';
import { GROW_CENTER_PATH, PUB_RES_PATH, WORKBENCH_PATH } from '@/utils/constant';
import { Layout, Modal } from 'antd';
import classNames from 'classnames';
import { observer } from 'mobx-react';
import React, { useEffect } from 'react';
import { renderRoutes } from 'react-router-config';
import { useHistory, useLocation } from 'react-router-dom';
import Header from '../components/Header';
import LeftMenu from '../components/LeftMenu';
import Toolbar from '../components/Toolbar';
import style from './style.module.less';
import LoginModal from '@/pages/User/LoginModal';
import GlobalServerModal from '@/components/GlobalSetting/GlobalServerModal';
import StartMinApp from '@/components/MinApp/StartMinApp';
import { HotkeysProvider } from 'react-hotkeys-hook';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { get_session } from '@/api/user';
import { remove_info_file } from '@/api/local_api';
import { exit } from '@tauri-apps/api/process';
import PasswordModal from '@/components/PasswordModal';
import Profile from '@/components/Profile';
import { request } from '@/utils/request';
import * as fsApi from '@/api/fs';
import { update as update_user } from '@/api/user';
import { AdminLoginModal } from '@/pages/User/AdminLoginModal';
import JoinModal from '@/pages/Workbench/components/JoinModal';
import UpdateResumeModal from '@/pages/User/UpdateResumeModal';
import AppStoreDetailModal from '@/pages/Workbench/components/userapp/AppStoreDetailModal';
import TestcaseDetailModal from '@/pages/Project/Testcase/TestcaseDetailModal';
import CreateTestCaseModal from "@/pages/Project/Testcase/CreateModal";
import RequirementDetailModal from '@/pages/Project/Requirement/RequirementDetailModal';
import CreateRequirementModal from "@/pages/Project/Requirement/CreateModal";
import IssueDetailModal from '@/pages/Issue/IssueDetailModal';
import CreateIssueModal from '@/pages/Issue/CreateModal';
import IdeaTipModal from '@/pages/Idea/IdeaTipModal';
import CreateBulletinModal from '@/pages/Project/ChatAndComment/components/CreateBulletinModal';
import ViewBulletinModal from '@/pages/Project/ChatAndComment/components/ViewBulletinModal';
import PagesModal from '@/pages/Project/Home/components/PagesModal';
import { ISSUE_TAB_LIST_TYPE, LinkBugInfo, LinkIdeaPageInfo, LinkSpritInfo, LinkTaskInfo } from '@/stores/linkAux';
import { ISSUE_TYPE_TASK, link_sprit } from '@/api/project_issue';
import CreatedOrJoinProject from '@/components/LeftMenu/CreatedOrJoinProject';
import InviteProjectMember from '@/components/LeftMenu/InviteProjectMember';
import CreatedOrJoinOrg from '@/components/LeftMenu/CreatedOrJoinOrg';
import InviteOrgMember from '@/components/LeftMenu/InviteOrgMember';
import EditReviewModal from '@/pages/Project/ChatAndComment/components/EditReviewModal';
import { useTranslation } from "react-i18next";

const { Content } = Layout;

const BasicLayout: React.FC<{ route: IRouteConfig }> = ({ route }) => {
  const history = useHistory();
  const { pathname } = useLocation();

  const { t } = useTranslation();

  const userStore = useStores('userStore');
  const projectStore = useStores('projectStore');
  const projectModalStore = useStores('projectModalStore');
  const orgStore = useStores('orgStore');
  const noticeStore = useStores('noticeStore');
  const appStore = useStores('appStore');
  const pubResStore = useStores("pubResStore")
  const linkAuxStore = useStores('linkAuxStore');
  const memberStore = useStores('memberStore');

  noticeStore.setHistory(history);

  const location = useLocation();
  const urlParams = new URLSearchParams(location.search);
  const type = urlParams.get('type');


  const uploadUserLogo = async (data: string | null) => {
    if (data === null) {
      return;
    }
    //上传文件
    const uploadRes = await request(fsApi.write_file_base64(userStore.sessionId, userStore.userInfo.userFsId, "portrait.png", data, ""));
    console.log(uploadRes);
    if (!uploadRes) {
      return;
    }
    //设置文件owner
    const ownerRes = await request(fsApi.set_file_owner({
      session_id: userStore.sessionId,
      fs_id: userStore.userInfo.userFsId,
      file_id: uploadRes.file_id,
      owner_type: fsApi.FILE_OWNER_TYPE_USER_PHOTO,
      owner_id: userStore.userInfo.userId,
    }));
    if (!ownerRes) {
      return;
    }
    //设置头像url
    const logoUri = `fs://localhost/${userStore.userInfo.userFsId}/${uploadRes.file_id}/portrait.png`;
    const updateRes = await request(update_user(userStore.sessionId, {
      display_name: userStore.userInfo.displayName,
      logo_uri: logoUri,
    }));
    if (updateRes) {
      userStore.showChangeLogo = false;
    }
    userStore.updateLogoUri(logoUri);
  };

  useEffect(() => {
    userStore.isResetPassword = (type === 'resetPassword');
  });

  useEffect(() => {
    if (userStore.sessionId == "") {
      return;
    }
    const t = setInterval(() => {
      get_session().then(sessInRust => {
        if (sessInRust == "") {
          userStore.logout();
        }
      });
    }, 2000);

    return () => clearInterval(t);
  }, [userStore.sessionId]);

  return (
    <HotkeysProvider>
      <Layout className={style.basicLayout}>
        {appStore.simpleLayout == false && (
          <LeftMenu />
        )}
        <Layout>
          <Header />
          <ErrorBoundary>
            <Content
              className={classNames(
                style.basicContent,
                pathname !== WORKBENCH_PATH && style.showbottomnav,
              )}
            >
              {renderRoutes(route.routes, { sessionId: userStore.sessionId, projectId: projectStore.curProjectId })}
            </Content>
          </ErrorBoundary>
          {projectStore.curProjectId != "" && <Toolbar />}
          {projectStore.curProjectId != "" && <BottomNav />}
        </Layout>
        {userStore.showUserLogin && <LoginModal />}
        {appStore.showGlobalServerModal && <GlobalServerModal />}
        {appStore.openMinAppParam != null && <StartMinApp />}
        {userStore.showLogout == true && (
          <Modal
            open
            mask={false}
            title={t("user.logout")}
            onCancel={() => userStore.showLogout = false}
            onOk={() => {
              userStore.logout();
              userStore.showLogout = false;
              projectStore.setCurProjectId("");
              orgStore.setCurOrgId("");
              if (location.pathname.startsWith(WORKBENCH_PATH) || location.pathname.startsWith(PUB_RES_PATH)) {
                //do nothing
              } else {
                if (appStore.vendorCfg?.ability.enable_work_bench) {
                  history.push(WORKBENCH_PATH);
                }else if(appStore.vendorCfg?.ability.enable_grow_center && appStore.vendorCfg.grow_center.force_show) {
                  history.push(GROW_CENTER_PATH);
                }
              }
            }}
          >
            <p style={{ textAlign: 'center' }}>{t("user.logoutMsg")}</p>
          </Modal>
        )}
        {appStore.showExit == true && (
          <Modal open title={t("header.exit")} mask={false}
            okText={t("header.exit")} okButtonProps={{ danger: true }}
            onCancel={e => {
              e.stopPropagation();
              e.preventDefault();
              appStore.showExit = false;
            }}
            onOk={e => {
              e.stopPropagation();
              e.preventDefault();
              async function func() {
                await remove_info_file();
                await exit(0);
              }
              func();
            }}>
            {t("header.exitMsg")}
          </Modal>
        )}
        {userStore.showChangePasswd && (
          <PasswordModal visible={userStore.showChangePasswd} onCancel={() => userStore.showChangePasswd = false} />
        )}
        {userStore.showChangeResume && (
          <UpdateResumeModal onClose={() => userStore.showChangeResume = false} />
        )}
        {userStore.showChangeLogo == true && (
          <Profile
            visible={userStore.showChangeLogo}
            defaultSrc={userStore.userInfo.logoUri ?? ""}
            onCancel={() => userStore.showChangeLogo = false}
            onOK={(data: string | null) => uploadUserLogo(data)}
          />
        )}
        {userStore.showAdminLogin == true && (
          <AdminLoginModal onClose={() => userStore.showAdminLogin = false} />
        )}
        {appStore.showJoinModal == true && (
          <JoinModal onClose={() => appStore.showJoinModal = false} />
        )}
        {pubResStore.showAppId != "" && <AppStoreDetailModal />}

        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.testCaseId != "" && (
          <TestcaseDetailModal projectInfo={projectStore.getProject(projectModalStore.projectId)!} myUserId={userStore.userInfo.userId}
            testCaseId={projectModalStore.testCaseId}
            testCaseTab={projectModalStore.testCaseTab} testCaseLinkSpritId={projectModalStore.testCaseLinkSpritId}
            onClose={() => {
              projectModalStore.projectId = "";
              projectModalStore.testCaseId = "";
              projectModalStore.testCaseTab = "detail";
              projectModalStore.testCaseLinkSpritId = "";
            }}
            onChangeTab={newTab => projectModalStore.testCaseTab = newTab} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.createTestCase == true && (
          <CreateTestCaseModal
            projectInfo={projectStore.getProject(projectModalStore.projectId)!}
            createTestCaseParentFolderId={projectModalStore.createTestCaseParentFolderId}
            createTestCaseEnableFolder={projectModalStore.createTestCaseEnableFolder}
            onCancel={() => projectModalStore.setCreateTestCase(false, "", false)}
            onOk={() => {
              projectModalStore.projectId = "";
              projectModalStore.setCreateTestCase(false, "", false);
            }} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.requirementId != "" && (
          <RequirementDetailModal projectInfo={projectStore.getProject(projectModalStore.projectId)!} tagList={projectStore.getProject(projectModalStore.projectId)!.tag_list}
            myUserId={userStore.userInfo.userId}
            requirementId={projectModalStore.requirementId} requirementTab={projectModalStore.requirementTab}
            onClose={() => {
              projectModalStore.projectId = "";
              projectModalStore.requirementId = "";
              projectModalStore.requirementTab = "detail";
            }}
            onChange={newTab => projectModalStore.requirementTab = newTab}
            onClickTask={(projectId, issueId) => linkAuxStore.goToLink(new LinkTaskInfo("", projectId, issueId), history)} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.createRequirement == true && (
          <CreateRequirementModal projectInfo={projectStore.getProject(projectModalStore.projectId)!}
            onCancel={() => projectModalStore.createRequirement = false}
            onOk={(requirementId, requirementTab) => {
              projectModalStore.projectId = "";
              projectModalStore.createRequirement = false;
              projectModalStore.requirementId = requirementId;
              projectModalStore.requirementTab = requirementTab;
            }} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.issueId != "" && (
          <IssueDetailModal projectInfo={projectStore.getProject(projectModalStore.projectId)!}
            tagList={projectStore.getProject(projectModalStore.projectId)!.tag_list}
            myUserId={userStore.userInfo.userId} myDisplayName={userStore.userInfo.displayName} myLogoUri={userStore.userInfo.logoUri}
            issueType={projectModalStore.issueType}
            issueId={projectModalStore.issueId}
            issueTab={projectModalStore.issueTab}
            onClose={() => projectModalStore.setIssueIdAndType("", 0)}
            onChange={newTab => projectModalStore.issueTab = newTab}
            onClickIssue={(projectId, issueId, issueType) => {
              if (issueType == ISSUE_TYPE_TASK) {
                linkAuxStore.goToLink(new LinkTaskInfo("", projectId, issueId), history);
              } else {
                linkAuxStore.goToLink(new LinkBugInfo("", projectId, issueId), history);
              }
            }} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.createIssue == true && (
          <CreateIssueModal projectInfo={projectStore.getProject(projectModalStore.projectId)!}
            createIssueType={projectModalStore.createIssueType}
            createIssueLinkSpritId={projectModalStore.createIssueLinkSpritId}
            onCancel={() => projectModalStore.setCreateIssue(false, 0, "")}
            onOk={(issueId) => {
              const f = async () => {
                if (projectModalStore.createIssueLinkSpritId != "" && projectStore.isAdmin) {
                  await request(link_sprit(userStore.sessionId, projectStore.curProjectId, issueId, projectModalStore.createIssueLinkSpritId));
                  linkAuxStore.goToLink(new LinkSpritInfo("", projectStore.curProjectId, projectModalStore.createIssueLinkSpritId), history);
                } else {
                  if (projectModalStore.createIssueType == ISSUE_TYPE_TASK) {
                    linkAuxStore.goToTaskList({
                      stateList: [],
                      execUserIdList: [],
                      checkUserIdList: [],
                      tabType: ISSUE_TAB_LIST_TYPE.ISSUE_TAB_LIST_ALL,
                    }, history);
                  } else {
                    linkAuxStore.goToBugList({
                      stateList: [],
                      execUserIdList: [],
                      checkUserIdList: [],
                      tabType: ISSUE_TAB_LIST_TYPE.ISSUE_TAB_LIST_ALL,
                    }, history);
                  }
                }
                projectModalStore.projectId = "";
                projectModalStore.setCreateIssue(false, 0, "");
              };
              f();
            }}
          />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.ideaKeyword != "" && (
          <IdeaTipModal projectInfo={projectStore.getProject(projectModalStore.projectId)!} ideaKeyword={projectModalStore.ideaKeyword}
            onCancel={() => projectModalStore.ideaKeyword = ""}
            onOk={() => {
              const f = async () => {
                linkAuxStore.goToLink(new LinkIdeaPageInfo("", projectStore.curProjectId, "", [projectModalStore.ideaKeyword]), history);
                projectModalStore.ideaKeyword = "";
              };
              f();
            }} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.createBulletin == true && (
          <CreateBulletinModal projectInfo={projectStore.getProject(projectModalStore.projectId)!} onClose={() => projectModalStore.createBulletin = false} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.createReview == true && (
          <EditReviewModal projectInfo={projectStore.getProject(projectModalStore.projectId)!}
            memberList={memberStore.memberList.map(item => item.member)}
            onClose={() => projectModalStore.createReview = false} />
        )}
        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.bulletinId != "" && (
          <ViewBulletinModal projectInfo={projectStore.getProject(projectModalStore.projectId)!} bulletinId={projectModalStore.bulletinId}
            onClose={() => projectModalStore.bulletinId = ""} />
        )}

        {projectModalStore.projectId != "" && projectStore.getProject(projectModalStore.projectId) != undefined && projectModalStore.pagesEntryId != "" && projectModalStore.pagesFileId != "" && (
          <PagesModal projectInfo={projectStore.getProject(projectModalStore.projectId)!!} fileId={projectModalStore.pagesFileId}
            entryId={projectModalStore.pagesEntryId} entryTitle={"静态网页"}
            onClose={() => {
              projectModalStore.projectId = "";
              projectModalStore.pagesEntryId = "";
              projectModalStore.pagesFileId = "";
            }} />
        )}



        {appStore.showCreateOrJoinProject && <CreatedOrJoinProject
          visible={appStore.showCreateOrJoinProject}
          onChange={(val) => (appStore.showCreateOrJoinProject = val)}
        />}
        {projectStore.curProjectId != "" && memberStore.showInviteMember && <InviteProjectMember
          visible={memberStore.showInviteMember}
          onChange={(val) => memberStore.showInviteMember = val} />
        }

        {appStore.showCreateOrJoinOrg && <CreatedOrJoinOrg
          visible={appStore.showCreateOrJoinOrg}
          onChange={(val) => (appStore.showCreateOrJoinOrg = val)}
        />}

        {orgStore.curOrgId != "" && orgStore.showInviteMember && <InviteOrgMember visible={orgStore.showInviteMember} onChange={val => orgStore.showInviteMember = val} />}
      </Layout>
    </HotkeysProvider>
  );
};

export default observer(BasicLayout);
